package la.ge.server;


import java.io.FileInputStream;
import java.io.InputStream;

import la.ge.server.common.XStreamFactory;
import la.ge.server.conf.ServerSetting;
import la.ge.server.conf.ServerSettingFactory;

import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.handler.ResourceHandler;
import org.mortbay.jetty.servlet.Context;
import org.mortbay.jetty.servlet.ServletHolder;

public class GeServer {

	private static Log logger = LogFactory.getLog( GeServer.class );
 
	public static void main(String[] args) {
		
		ServerSetting serverSetting = null;
		
		
		//load setting file
		InputStream fileInStream = null; 
		try {
			fileInStream = new FileInputStream( "./conf/setting.xml" );
			serverSetting = (ServerSetting) XStreamFactory.create().fromXML( fileInStream );
		}
		catch( Exception e ) {//load failed, will use default setting
			logger.warn( "load failed, will use default setting", e );
			serverSetting = ServerSettingFactory.createDefault();
		}
		finally {
			IOUtils.closeQuietly( fileInStream );
		}
		
		logger.debug( "setting:" + XStreamFactory.create().toXML( serverSetting ) );
		
		//build GEServer context
		GeServerContext	geServerContext = new GeServerContext();
		
		//config server
		Server server = new Server( serverSetting.listeningPort );
		Context context = new Context( server, "/", Context.SESSIONS );
		context.setAttribute( GeServerContext.ATTRIB_NAME, geServerContext );
		for(Class servletClass : geServerContext.getServletList()) {
			context.addServlet( new ServletHolder( servletClass ),
					geServerContext.getServletPath( servletClass ) );
		}
		
		//config static web resource
        ResourceHandler resource_handler=new ResourceHandler();
        resource_handler.setResourceBase( "./static_web" );
        server.addHandler( resource_handler );        

		try {
			server.start();
			server.join();
		} catch (Exception e) {
			logger.error( e, e );
		}

	}

}
